package com.canbot.u05.activity.presidemode.newcode;

import android.app.Dialog;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.canbot.u05.R;
import com.canbot.u05.activity.presidemode.newcode.adapter.NExeStepAdapter;
import com.canbot.u05.activity.presidemode.newcode.bean.EDirection;
import com.canbot.u05.activity.presidemode.newcode.bean.HostItemBean;
import com.canbot.u05.activity.presidemode.newcode.bean.HostModuleData;
import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil;
import com.canbot.u05.activity.presidemode.newcode.interfaces.ICircleClick;
import com.canbot.u05.activity.presidemode.newcode.interfaces.IResponse;
import com.canbot.u05.activity.presidemode.newcode.view.HeadCommonView;
import com.canbot.u05.activity.presidemode.newcode.view.UnCircleImageView;
import com.canbot.u05.control.Cmd;
import com.canbot.u05.control.RobotMgr;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NHostExeActivity extends BaseHostActivity {
    public static final int TASK_INDEX = 0;
    public static final int TASK_PAUSE = 1;
    public static final int TASK_CONTINUE = 2;
    public static final int TASK_NEXT = 3;
    public static final int TASK_STOP = 4;
    public static final int TASK_AUTO = 5;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.commonHead)
    HeadCommonView commonHead;
    @BindView(R.id.left_up)
    UnCircleImageView leftUp;
    @BindView(R.id.left_down)
    UnCircleImageView leftDown;
    @BindView(R.id.left_left)
    UnCircleImageView leftLeft;
    @BindView(R.id.left_right)
    UnCircleImageView leftRight;
    @BindView(R.id.right_up)
    UnCircleImageView rightUp;
    @BindView(R.id.right_down)
    UnCircleImageView rightDown;
    @BindView(R.id.right_left)
    UnCircleImageView rightLeft;
    @BindView(R.id.right_right)
    UnCircleImageView rightRight;
    @BindView(R.id.head_go_home)
    Button headGoHome;
    @BindView(R.id.btn_decreace)
    Button btnDecreace;
    @BindView(R.id.text_speed)
    TextView textSpeed;
    @BindView(R.id.btn_increase)
    Button btnIncrease;
    @BindView(R.id.play)
    TextView play;
    @BindView(R.id.pause)
    TextView pause;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.continue_play)
    Button continuePlay;

    private short hAngle = 0;
    private short moveSpeed = 300;
    private short vAngle = 0;
    private HostModuleData hostModuleData;
    private NExeStepAdapter nExeStepAdapter;
    private List<HostItemBean> stringList = new ArrayList<>();
    private ToastTools toastTools;
    private int currentPosition;
    private int speedIndex = 0;

    @OnClick({R.id.btn_decreace, R.id.btn_increase, R.id.head_go_home, R.id.play, R.id.pause, R.id.next, R.id.continue_play})
    public void btnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_decreace:
                --speedIndex;
                setSpeed();
                break;
            case R.id.btn_increase:
                ++speedIndex;
                setSpeed();
                break;
            case R.id.head_go_home:
                vAngle = hAngle = 0;
                RobotMgr.getInstance().headControl(Cmd.Joint_Ver, vAngle);
                RobotMgr.getInstance().headControl(Cmd.Joint_Hor, hAngle);
                break;
            case R.id.play:
                exeTask(TASK_CONTINUE, "pause_continue");
                break;
            case R.id.pause:
                if (isPlay) {
                    exeTask(TASK_PAUSE, "pause_continue");
                }
                break;
            case R.id.next:
                exeTask(TASK_NEXT, "next");
                break;
            case R.id.continue_play:
                exeTask(TASK_AUTO, continuePlay.isSelected() ? 0 : 1);
                break;
        }
    }

    private Dialog dialogLoading;
    private boolean isPlay = false;

    private void exeTask(int runType, Object data) {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        NetLoadUtil.exeNodeTask(this, new IResponse<String>() {
            @Override
            public void onSucusse(String result) {
                LoadingDialogUtils.closeDialog(dialogLoading);
                runOnUiThread(() -> {
                    switch (runType) {
                        case TASK_INDEX:
                            isPlay = true;
                            currentPosition = Integer.valueOf(data.toString());
                            nExeStepAdapter.setExePos(currentPosition);
                            nExeStepAdapter.notifyDataSetChanged();
                            break;
                        case TASK_AUTO:
                            continuePlay.setSelected(!continuePlay.isSelected());
                            if (continuePlay.isSelected()) {
                                continuePlay.setText(getString(R.string.continue_play));
                            } else {
                                continuePlay.setText(getString(R.string.one_play));
                            }
                            break;
                        case TASK_PAUSE:
                            isPlay = false;
                            break;
                        case TASK_NEXT:
                        case TASK_CONTINUE:
                            isPlay = true;
                            break;
                        case TASK_STOP:
                            isPlay = false;
                            finish();
                            break;
                    }
                });
            }

            @Override
            public void onFailuer(String result) {
                LoadingDialogUtils.closeDialog(dialogLoading);
                ToastTools.newInstance(getApplicationContext()).showText(result);
            }
        }, runType, data);
    }

    /**
     * 消息发布者位置
     * ReceiveData
     * mHandler
     * case MsgType.MOBILE_PAD_MAP_TASK:
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMapEvent(StringMsgBean bean) {
        switch (bean.getMsgType()) {
            case MsgType.COMPERE_RAN_TASK_END:
                LoadingDialogUtils.closeDialog(dialogLoading);
                toastTools.showText(getString(R.string.task_compeled));
                nExeStepAdapter.setExePos(-1);
                if (currentPosition >= 0 && currentPosition < stringList.size()) {
                    HostItemBean hostItemBean = stringList.get(currentPosition);
                    hostItemBean.setPlay(false);
                }
                nExeStepAdapter.notifyDataSetChanged();
                break;
            case MsgType.COMPERE_RAN_TASK_STATE:
                String msgData = bean.getMsgData();
                toastTools.showText("msgData:" + msgData);
                break;
            case MsgType.COMPERE_RAN_TASK_POSITION:
                msgData = bean.getMsgData();
                currentPosition = Integer.valueOf(msgData);
                nExeStepAdapter.setExePos(currentPosition);
                nExeStepAdapter.notifyDataSetChanged();
                break;

        }
    }

    private void setSpeed() {
        if (speedIndex <= 0) {
            speedIndex = 0;
        } else if (speedIndex > 5) {
            speedIndex = 5;
        }
        switch (speedIndex) {
            case 0:
                textSpeed.setText(String.valueOf(1));
                moveSpeed = 300;
                break;
            case 1:
                textSpeed.setText(String.valueOf(2));
                moveSpeed = 400;
                break;
            case 2:
                textSpeed.setText(String.valueOf(3));
                moveSpeed = 500;
                break;
            case 3:
                textSpeed.setText(String.valueOf(4));
                moveSpeed = 600;
                break;
            case 4:
                textSpeed.setText(String.valueOf(5));
                moveSpeed = 700;
                break;
            case 5:
                textSpeed.setText(String.valueOf(6));
                moveSpeed = 800;
                break;
        }
    }

    private void handlerHeadAngle(EDirection eDirection) {
        if (hAngle > 60) {
            hAngle = 60;
        } else if (hAngle < -60) {
            hAngle = -60;
        }
        if (vAngle > 30) {
            vAngle = 30;
        } else if (vAngle < -30) {
            vAngle = -30;
        }
        switch (eDirection) {
            case UP:
                vAngle -= 10;
                RobotMgr.getInstance().headControl(Cmd.Joint_Ver, vAngle);
                break;
            case DOWN:
                vAngle += 10;
                RobotMgr.getInstance().headControl(Cmd.Joint_Ver, vAngle);
                break;
            case LEFT:
                hAngle += 15;
                RobotMgr.getInstance().headControl(Cmd.Joint_Hor, hAngle);
                break;
            case RIGHT:
                hAngle -= 15;
                RobotMgr.getInstance().headControl(Cmd.Joint_Hor, hAngle);
                break;
        }
    }

    private void handlerAngle(EDirection eDirection) {
        switch (eDirection) {
            case UP:
                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_qianjin);
                break;
            case RIGHT:
                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_youzhuan);
                break;
            case LEFT:
                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_zuozhuan);
                break;
            case DOWN:
                RobotMgr.getInstance().keyControl(moveSpeed, Cmd.Key_houtui);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private static final String TAG = "NHostExeActivity";

    @Override
    protected void initEventData() {
        toastTools = ToastTools.newInstance(getApplicationContext());
        EventBus.getDefault().register(this);
        initHeadCommon();
        initCircleControl();
        recycleView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        nExeStepAdapter = new NExeStepAdapter(stringList, this, (position, v) -> {
            Log.e(TAG, "initEventData: " + position + "  " + currentPosition);
            if (currentPosition != position) {
                HostItemBean hostItemBean = stringList.get(currentPosition);
                hostItemBean.setPlay(false);
                HostItemBean hostItemBean1 = stringList.get(position);
                hostItemBean1.setPlay(true);
                exeTask(TASK_INDEX, position);
            } else {
                HostItemBean hostItemBean = stringList.get(currentPosition);
                if (!hostItemBean.isPlay()) {
                    hostItemBean.setPlay(true);
                    exeTask(TASK_INDEX, position);
                }
            }
        });
        recycleView.setAdapter(nExeStepAdapter);
        initIntent();
    }

    private void initCircleControl() {
        ICircleClick iCircleClickDirection = new ICircleClick() {
            @Override
            public void onClick(View v) {
            }

            @Override
            public void onPress(View v) {
                Log.e(TAG, "onPress: ");
                UnCircleImageView circleImageView = (UnCircleImageView) v;
                EDirection eDirection = circleImageView.geteDirection();
                handlerAngle(eDirection);
            }

            @Override
            public void onUp() {
                Log.e(TAG, "onUp: ");
                RobotMgr.getInstance().keyControl(Cmd.Key_tingzhi);
            }
        };
        leftUp.setiCircleClick(iCircleClickDirection);
        leftDown.setiCircleClick(iCircleClickDirection);
        leftRight.setiCircleClick(iCircleClickDirection);
        leftLeft.setiCircleClick(iCircleClickDirection);

        ICircleClick iCircleClickHead = new ICircleClick() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: ");
            }

            @Override
            public void onPress(View v) {
                Log.e(TAG, "onPress: ");
                UnCircleImageView circleImageView = (UnCircleImageView) v;
                EDirection eDirection = circleImageView.geteDirection();
                handlerHeadAngle(eDirection);
            }

            @Override
            public void onUp() {
                RobotMgr.getInstance().keyControl(Cmd.Key_tingzhi);
            }
        };
        rightUp.setiCircleClick(iCircleClickHead);
        rightDown.setiCircleClick(iCircleClickHead);
        rightLeft.setiCircleClick(iCircleClickHead);
        rightRight.setiCircleClick(iCircleClickHead);
    }

    private void initHeadCommon() {
        commonHead.setiHeadCommonClick(pos -> {
            exit();
        });
    }

    private void exit() {
        exeTask(TASK_STOP, "stop");
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            hostModuleData = (HostModuleData) intent.getSerializableExtra(DATA);
            if (hostModuleData != null) {
                commonHead.setCenterTitle(hostModuleData.getTaskName());
                stringList.addAll(hostModuleData.getTaskNodes());
                nExeStepAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_nhost_exe;
    }


}
